package lx.springBoot.service.impl;

import common.*;
import lx.springBoot.dao.UserDAO;
import lx.springBoot.entry.User;
import lx.springBoot.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by lx on 2017/7/3.
 */
@Service("userService")
public class UserServiceImpl implements UserService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private UserDAO userDao;

    @Override
    public Result<User> getUser(User user){
        try{
            logger.info("getUer info == " + user );
            return Result.sucess(userDao.findById(user.getId()));
        }catch (Exception e){
            logger.info("getUser "+ e.getMessage());
           return Result.error(CommonCode.ERROR.getCode(),CommonCode.ERROR.getMes());
        }
    }

    @Override
    public Result<User> login(String loginName, String pwd) {
        if(StringUtils.isBlank(loginName) || StringUtils.isBlank(pwd)){
            return Result.error(CommonCode.USERERROR.getCode(),CommonCode.USERERROR.getMes());
        }
        List<User> users = userDao.findByLoginName(loginName);
        if(! CollectionUtil.isEntry(users) || users.size() > 1){
            return Result.error(CommonCode.USERNOT.getCode(),CommonCode.USERNOT.getMes());
        }
        User user = users.get(0);
        if(! MD5Util.MD5(pwd).toUpperCase().equals(user.getPassword().toUpperCase())){
            return Result.error(CommonCode.USERPWDERROR.getCode(),CommonCode.USERPWDERROR.getMes());
        }
        return Result.sucess(user);
    }

    @Override
    public Result<User> getById(Long id) {
        return Result.sucess(userDao.findById(id));
    }
}